package XMLProcessing;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

import Exceptions.TableNotFoundException;


public class DatabaseProcessing {

	public static String addTable(String table) {
		try {
		String filepath = "XMLFiles\\Sysobjects.xml";
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder;
		docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(filepath);
		// get the root
		Node root = doc.getFirstChild();
		Node refChild = null;
		Element tbl = doc.createElement("Table");
		Element name = doc.createElement("Name");
		Element file = doc.createElement("File");
		Node namev = doc.createTextNode(table);
		Node filev = doc.createTextNode("XMLFiles\\" + table+".xml");
		name.appendChild(namev);
		file.appendChild(filev);
		tbl.appendChild(name);
		tbl.appendChild(file);
		String tblname;
		NodeList nList = doc.getElementsByTagName("Table");
		for (int temp = 0; temp < nList.getLength(); temp++) {
			   Node nNode = nList.item(temp);
			   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
			      Element eElement = (Element) nNode;
			      
			      tblname = getTagValue("Name", eElement);
			      if(tblname.compareTo(table) > 0) {
			    	  refChild = nNode;
			    	  temp = nList.getLength();
			      }
			   }
			}
		if(refChild != null)
			root.insertBefore(tbl,refChild);
		else 
			root.appendChild(tbl);
	
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(filepath));
		transformer.transform(source, result);
		return "XMLFiles\\" + table + ".xml";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String retrieveTable(String t) throws TableNotFoundException {
		try {
			String name, value;
			File fXmlFile = new File("XMLFiles\\Sysobjects.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();
			NodeList nList = doc.getElementsByTagName("Table");

			for (int temp = 0; temp < nList.getLength(); temp++) {

				Node nNode = nList.item(temp);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {

					Element eElement = (Element) nNode;
					name = getTagValue("Name", eElement);
					value = getTagValue("File", eElement);
					if(t.equals(name))
						return value;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		throw new TableNotFoundException(t);
	}

	public static String removeTable(String t) {
		try {
			String name;
			File fXmlFile = new File("XMLFiles\\Sysobjects.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();
			NodeList nList = doc.getElementsByTagName("Table");
			Node root = doc.getFirstChild();
			
			for (int temp = 0; temp < nList.getLength(); temp++) {
				Node nNode = nList.item(temp);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) nNode;
					name = getTagValue("Name", eElement);
					if(t.equals(name)) {
						root.removeChild(nNode);
						temp--;
					}
				}
			}
		
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File("XMLFiles\\Sysobjects.xml"));
			transformer.transform(source, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static String getTagValue(String sTag, Element eElement) {
		NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
				.getChildNodes();

		Node nValue = (Node) nlList.item(0);

		return nValue.getNodeValue();
	}
	
}
